import router from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration
const generateTitle = (title) => {
  const hasKey = window.vm.$i18n.te('route.' + title)
  if (hasKey) {
    // $t :this method from vue-i18n, inject in @/lang/index.js
    const translatedTitle = window.vm.$i18n.t('route.' + title)

    return translatedTitle
  }
  return title
}
const whiteList = ['/login'] // no redirect whitelist
router.beforeEach((to, from, next) => {
  // start progress bar
  NProgress.start()

  // determine whether the user has logged in
  const hasToken = getToken() || false
  if (hasToken && hasToken != 'undefined') {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next('/dashboard')
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          store.dispatch('user/getInfo').then((data) => {
            next()
          })
        } catch (error) {
          // 此处应该跳转到登录页面
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach((to) => {
  // finish progress bar
  // set page title
  document.title = generateTitle(to.meta.title)
  NProgress.done()
})
